package netty;

import netty.client.RPCProxyFactoryBean;
import netty.util.PackageClassUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 动态加载代理bean到Springbean工厂
 *
 * @author Administrator
 */
@Configuration
public class NettyBeanScanner implements BeanFactoryPostProcessor
{
	private DefaultListableBeanFactory beanFactory;

	private String basePackage = "netty.service";

	private String clientName = "nettyClient";

	public NettyBeanScanner()
	{
	}

	/**
	 * 注册Bean到Spring的bean工厂
	 */
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
		throws BeansException
	{
		this.beanFactory = (DefaultListableBeanFactory)beanFactory;
		//注册Client
		List<String> resolverClass = PackageClassUtils.resolver(basePackage);
		for (String clazz : resolverClass)
		{
			String simpleName = "";
			if (clazz.lastIndexOf('.') != -1)
			{
				simpleName = clazz.substring(clazz.lastIndexOf('.') + 1);
			}
			else
			{
				simpleName = clazz;
			}
			/**
			 * <bean id="simpleName" class="RPCProxyFactoryBean">
			 *     <property name="interfaceClass" value="clazz"/>
			 *     <property name="client" ref="clientName"/>
			 * </bean>
			 */
			BeanDefinitionBuilder gd = BeanDefinitionBuilder.genericBeanDefinition(RPCProxyFactoryBean.class);
			gd.addPropertyValue("interfaceClass", clazz);
			gd.addPropertyReference("client", clientName);
			this.beanFactory.registerBeanDefinition(simpleName, gd.getRawBeanDefinition());
		}
	}
}
